package com.example.shopping.controller;

import com.example.shopping.config.Validator;
import com.example.shopping.entity.User;
import com.example.shopping.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@Controller
@RequestMapping("/ucenter")
public class UcenterController {

    @Autowired
    private UserService userService;

    @GetMapping("")
    public String index(HttpSession session, Model model) {
        //判断是否已登录
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        model.addAttribute("user", user);
        return "userinfo";
    }

    //ucenter/update
    @PostMapping("/update")
    @ResponseBody
    public String update(HttpSession session, Model model, String email,
                         String telphone, String avatar, String newPassword, String confirmPassword) {
        //判断是否已登录
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        if(!Objects.equals(newPassword, confirmPassword)){
            System.out.println(newPassword+"|"+confirmPassword);
            return "fail:两次密码不一致";
        }

        if (telphone != null && !telphone.isBlank() && !Validator.validatePhone(telphone)) {
            return "fail:手机号码不符合要求";
        }
        if (confirmPassword != null && !confirmPassword.isBlank()) {
            if (!Validator.validatePassword(newPassword)) {
                return "fail:密码不符合要求";
            }
        }
        if (telphone != null && !telphone.isBlank()) {
            user.setTelphone(telphone);
        }
        if(email!=null&&!email.isBlank()){
            user.setEmail(email);
        }

        if(avatar!=null&&!avatar.isBlank()){
            user.setAvatar(avatar);
        }
        if(newPassword!=null&&!newPassword.isBlank()){
            user.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
        }
        userService.updateUser(user);
        return "success";
    }
}
